package com.chilly.netty.websocket.action.reconnHeart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * websocket 实例
 * https://www.bilibili.com/video/BV1Q5411a7Hy?p=6
 * <p>
 * 通用handler，处理 I/O事件
 * Created by Chilly Cui on 2020/12/25.
 */
@ChannelHandler.Sharable //注解
public class HandlerClientReconnHeart extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 处理收到的消息
     *
     * @param ctx
     * @param msgByteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msgByteBuf) throws Exception {
        System.out.println("收到的消息：" + msgByteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 处理I/O事件的异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String strDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS"));
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是客户端通过 Active 方法发送的信息 " + strDateTime + "\r\n", CharsetUtil.UTF_8));
    }

    //断线重连
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        //System.out.println("服务端：" + incoming + "掉线");
        System.out.println(incoming + "掉线");

        //检测到掉线后，重新开始连接
        new AppClientReconnHeart("127.0.0.1", 18080).run();
    }

    //超时检测
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                System.out.println("客户端读消息包超时");
                //检测到读超时，就向服务器端发送一个消息包
                String strDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss SSS")).toString();
                ctx.writeAndFlush(Unpooled.copiedBuffer("我是心跳消息：" + strDate + "\r\n", CharsetUtil.UTF_8));
            }
        }
    }
}
